<template>
  <div
    class="v-editor-model-tree-select g-jc-sb g-pd-l-8"
    :class="{ _disable: disabled }"
  >
    <div class="g-one-line content">
      <template v-if="imageFullPath">
        <img
          class="g-m-r-4"
          style="height: 14px"
          :src="imageFullPath"
        />
      </template>
      <template v-if="!imageFullPath"><span class="placeholder">推荐图片尺寸为220px*150px</span></template>
    </div>

    <div
      v-if="selected && !disabled"
      style="border-left: 1px solid #ddd; line-height: 14px"
      class="g-pd-4 g-flex-0"
    >
      <div>
        <div>
          <img
            src="statics/icons/app/ImageShape.svg"
            class="g-pointer"
            @click="handleClick('add')"
          />
        </div>
      </div>
      <div class="g-m-t-4">
        <img
          src="statics/icons/app/iconmore.png"
          class="g-pointer"
          @click="handleClick('file')"
        />
      </div>
      <div class="g-m-t-4">
        <img
          src="statics/icons/app/iconreduce.png"
          class="g-pointer"
          :class="{ _disable: !row.value }"
          @click="handleClick('remove')"
        />
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { computed, ref, onMounted } from "vue";
import { localFile } from "@/localFile/LocalFile";
import { imageLibraryWindow } from "../../../imageLibrary";
import { modelService } from "@/modules/model/service";
import { PropertyKey } from "@/constants/Enums";
import { AttachedFileInfo } from "@/constants/types";

const emit = defineEmits<{
  (event: "changeImage", imgUrl: string, key: string): void;
}>();

const imageFullPath = ref("");

/**
 * 模型单选-树选择弹窗
 */
const props = defineProps<{
  row: any;
  selected?: boolean;
  projectId: string;
  modelId: string;
  configurationDisabled?: boolean;
}>();

onMounted(async () => {
  if (props.row.value) {
    const fileName = await getImageUrl(props.row.value);
    imageFullPath.value = modelService.getModelIcon(props.projectId, fileName);
  }
});

const disabled = computed(() => {
  return props.row.readonly || props.configurationDisabled;
});

async function getImageUrl(modelId) {
  const propertyValue = await modelService.getPropertyValuesById(props.projectId, modelId, [PropertyKey.Customization_AttachedFile_file]);
  const value = propertyValue.data![PropertyKey.Customization_AttachedFile_file]?.value as string;
  if (value) {
    const fileValue = JSON.parse(value);
    const filePath = fileValue.filePath;
    return filePath;
  } else {
    return "";
  }
}
async function handleRemove() {
  if (props.row.value) {
    modelService.removeModel(props.projectId, [props.row.value]); // 删除对应的模型
    imageFullPath.value = "";
    emit("changeImage", "", props.row.key);
  }
}

const handleClick = (type: string) => {
  switch (type) {
    case "add":
      handleAddImage();
      break;
    case "file":
      handleFileClick();
      break;
    case "remove":
      handleRemove();
      break;
    default:
      break;
  }
};

const handleAddImage = async () => {
  imageLibraryWindow.popup({ attrTip: "SelectImage", title: "选择图片", configuration: false }).then(async res => {
    if (res.url) {
      res.url = res.url.replace(/\\/g, "/");
      if (res.url.startsWith("/")) {
        res.url = res.url.slice(1);
      }
    }
    if (res.size?.includes("K")) {
      if (Number(res.size.replace("K", "")) / 1024 > 5) {
        app.$notify({
          type: "error",
          title: "提示",
          message: "图片大小不能超过5M"
        });
        return;
      }
    }
    if (res.size?.includes("M")) {
      if (Number(res.size.replace("M", "")) > 5) {
        app.$notify({
          type: "error",
          title: "提示",
          message: "图片大小不能超过5M"
        });
        return;
      }
    }
    if (!res.url) return;
    if (props.row.value) {
      modelService.removeModel(props.projectId, [props.row.value]); // 如果之前设置过图片，则该动作为替换，先删除之前图片对应的模型
    }
    let fileInfo: AttachedFileInfo = {
      filePath: "",
      icon: "",
      fileName: "",
      hostname: "",
      size: 0,
      width: 0,
      height: 0
    };
    fileInfo.filePath = res.url;
    const fileData = await modelService.uploadFile(props.projectId, res.url);
    fileInfo.icon = modelService.getModelIcon(props.projectId, fileData.newFileName);

    const modelId = (await addMetaConfigImageFile(fileInfo)) || "";
    emit("changeImage", modelId, props.row.key);
  });
};

const handleFileClick = async () => {
  const result = await localFile.chooseFile({
    filters: [
      {
        name: "图片",
        extensions: ["jpg", "jpeg", "png", "gif", "svg"]
      }
    ],
    loadBuffer: true
  });
  let filePath = result.files[0]?.path;
  let size = result.files[0]?.buffer?.byteLength;
  if (!filePath) return;
  if (props.row.value) {
    modelService.removeModel(props.projectId, [props.row.value]); // 如果之前设置过图片，则该动作为替换，先删除之前图片对应的模型
  }
  if (size && size / 1024 ** 2 > 5) {
    app.$notify({
      type: "error",
      title: "提示",
      message: "图片大小不能超过5M"
    });
    return;
  }
  let fileInfo: AttachedFileInfo | undefined;
  fileInfo = await localFile.readAttachedFileInfo(filePath);
  const modelId = (await addMetaConfigImageFile(fileInfo)) || "";
  emit("changeImage", modelId, props.row.key);
};

const addMetaConfigImageFile = async fileInfo => {
  const models = await modelService.addModelForMetaConfig(
    props.projectId,
    props.modelId,
    "Comment",
    ["Customization::AttachedFile"],
    fileInfo
  );
  if (models) {
    const targetModel = models.find(model => model.metaclass === "Comment"); // 只判断了metaclass，目前够用
    if (targetModel) {
      const fileName = await getImageUrl(targetModel.id);
      imageFullPath.value = modelService.getModelIcon(props.projectId, fileName);
      return targetModel.id;
    } else {
      console.error("缺少返回模型");
    }
  }
};
</script>
<style lang="scss" scoped>
.v-editor-model-tree-select {
  height: 100%;
  .content {
    text-overflow: ellipsis;
    white-space: nowrap;
    display: flex;
    align-items: center;
    > span {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
  .placeholder {
    color: #cccccc;
  }
}
._disable {
  cursor: not-allowed;
  background-color: #f5f7fa;
  // filter: grayscale(100);
}
</style>
